﻿param($computersListPath)

Import-Module ActiveDirectory
Import-Module -Force ..\ConfigurationDatabase\libConfigurationDatabase.psm1

$scriptEnvironmentShortName="QA6"

$crashDumpArchivePath=(Get-ConfigurationSetting -environmentShortName $environmentShortName -scope "Global"  -name "CrashDumpArchivePath").Value

workflow Collect-CrashDump($crashDumpArchivePath)
{
    
    if($computersListPath -ne $null)
    {
        $computers=Get-Content -Path $computersListPath
    }
    else
    {
        $computers=(Get-ADComputer -Filter {(name -notlike "*v-*")}).Name
    }
    
    foreach -Parallel ($computer in $computers)
    {
        if($computer -inotlike "*v-*")
        {
            $connectionTest=Test-Connection -Count 1 -ComputerName $computer -ErrorAction SilentlyContinue
            if($connectionTest)
            {
                Write-Output "Checking for crash dumps on $computer"
                $crashDumps=Get-ChildItem -Path "\\$computer\C$\windows\*.dmp"

                if($crashDumps -ne $null)
                {

                    if($connectionTest.ResponseTime -lt 100)
                    {
                        foreach($crashDump in $crashDumps)
                        {
                            $destinationPath="$crashDumpArchivePath\$computer`_" + $crashDump.LastWriteTime.GetDateTimeFormats("u").Replace(":","") + ".DMP"
                            if(-not(Test-Path -Path $destinationPath))
                            {
                                Write-Output "New crash dump found on $computer, copying to archive directory"
                                Copy-Item $crashDump -Destination $destinationPath
                            }
                            else
                            {
                                Write-Output "This crash dump for $computer was already collected"
                            }
                        }
                    }
                    else
                    {
                        Write-Output "Found crash dump on $computer but latency to computer is too high to copy"
                    }
                }

            }
            else
            {
                Write-Output "Cannot reach $computer"
            }
        }
        else
        {
            Write-Output "$computer is a service name,skipping."
        }
    }
}

Collect-CrashDump -crashDumpArchivePath $crashDumpArchivePath